package com.yanghui.agent.agentBytebuddy;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;

import java.io.File;
import java.lang.reflect.Modifier;

public class TestBytebuddy {

    public static void main(String[] args) throws Exception {
        intercept();
        createClass();
    }

    private static void createClass() throws Exception {
        DynamicType.Unloaded<?> dynamicType = new ByteBuddy()
                .subclass(Object.class)
                .name("com.yanghui.agent.agentBytebuddy.HelloWorld")
                .defineMethod("test", String.class, Modifier.PUBLIC)
                .intercept(FixedValue.value("Hello World!"))
                .make()
                ;
       File file = new File(TestBytebuddy.class.getResource("/").getPath() + "HelloWorld");
       System.out.println(file);
       dynamicType.saveIn(file);
       Class<?> clazz = dynamicType.load(TestBytebuddy.class.getClassLoader()).getLoaded();
       Object result = clazz.getMethod("test").invoke(clazz.newInstance());
       System.out.println(result);
    }

    private static void intercept() throws Exception {
        String helloWorld = new ByteBuddy().subclass(Object.class)
                .method(ElementMatchers.named("toString"))
                .intercept(FixedValue.value("Hello World!"))
                .make()
                .load(TestBytebuddy.class.getClassLoader())
                .getLoaded()
                .newInstance()
                .toString();
        System.out.println(helloWorld);
    }
}
